package com.apes.framework.rop.context;

import com.apes.framework.api.SpringManager;
import com.apes.framework.plugin.soe.core.context.SoeContext;
import com.apes.framework.util.DistributedLock;
import com.apes.oap.AbstractInterceptor;
import com.apes.oap.RopRequestContext;

public class RopRequestContextInterceptor extends AbstractInterceptor {

    public void beforeService(RopRequestContext ropRequestContext) {
        SoeContext.remove();
        RopContextHolder.put(ropRequestContext);
    }

    public void beforeResponse(RopRequestContext ropRequestContext) {
        RopContextHolder.remove();
        unlock();
    }

    /**
     * 不能在事务内释放锁，否则高并发下锁失效
     **/
    private void unlock() {
        DistributedLock distributedLock = SpringManager.getBean(DistributedLock.class);
        while (true) {
            String lockId = DistributedLock.poll();
            if (lockId == null) {
                break;
            }
            distributedLock.unlock(lockId);
        }
        DistributedLock.remove();
    }
}
